package com.talkweb.historylib.fraction;

import com.talkweb.historylib.ResourceTable;
import com.talkweb.historylib.provider.ImageShowProvider;
import com.talkweb.historylib.provider.PagerSliderChangedAdapter;
import com.talkweb.securitycamera.common.base.BaseFraction;
import com.talkweb.securitycamera.common.constans.Constant;
import com.talkweb.securitycamera.common.constans.FileType;
import com.talkweb.securitycamera.common.interfaces.entity.IBaseFileEntity;
import com.talkweb.securitycamera.utils.TimeUtils;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.TextTool;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @version 1.0.1
 * @description:
 * @program: security-camera
 * @Author xiaozhijun
 * @Date 2021/2/4 9:16
 */
public class ImageShowFraction extends BaseFraction {
    /**
     * 标记当前索引
     */
    private int initIndex;

    /**
     * 图片浏览组件
     */
    private PageSlider mImageShowPageSlide;

    /**
     * 图片统计与当前位置展示视图
     */
    private Text mImageShowCountText;

    private ImageShowProvider mImageShowProvider;

    private Image exitBtn;
    private Image delBtn;
    private Text nameText;

    private List<IBaseFileEntity> allDatas;

    public ImageShowFraction(int index) {
        this.initIndex = index;
    }

    @Override
    public int getLayoutId() {
        return ResourceTable.Layout_fraction_image_show;
    }

    @Override
    public void initializeComponent(Component component) {
        mImageShowPageSlide = findComponent(ResourceTable.Id_ohos_image_pager);
        mImageShowCountText = findComponent(ResourceTable.Id_text_count_title);
        exitBtn = findComponent(ResourceTable.Id_btn_exit_image);
        delBtn = findComponent(ResourceTable.Id_btn_del);
        nameText = findComponent(ResourceTable.Id_text_image_title);

        //先添加Page监听事件，再设置Provider提供数据，否则第一次界面显示无法监听到事件改变。
        mImageShowPageSlide.addPageChangedListener(new PagerSliderChangedAdapter() {

            @Override
            public void onPageChosen(int position) {
                final int currentPagePosition = mImageShowPageSlide.getCurrentPage();
                setImageCountTitle(currentPagePosition);
            }
        });

        exitBtn.setClickedListener(view -> {
            terminateAbility();
        });

        delBtn.setClickedListener(view -> {
            deletePicture();
        });
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        mImageShowProvider = new ImageShowProvider();
        initData();
        mImageShowProvider.setImageData(allDatas);
        mImageShowPageSlide.setProvider(mImageShowProvider);
        mImageShowPageSlide.setCurrentPage(initIndex);
        setImageCountTitle(initIndex);
    }

    public void initData() {
        allDatas = new ArrayList<>();
        //TOCHECK xiaoz 2021/2/5 测试数据需要修改
        for (int i = 0; i < 6; i++) {
            IBaseFileEntity entity = new IBaseFileEntity() {
                @Override
                public String getFilePath() {
                    return "/data/local/tmp/hiai/pic1.jpg";
                }

                @Override
                public String getCreateDuration() {

                    return TimeUtils.getTimeYYYYMMddHHmmss(System.currentTimeMillis() - new Random().nextLong());
                }

                @Override
                public String getFileName() {
                    return "图像" + new Random().nextInt(100);
                }

                @Override
                public FileType getFileType() {
                    return FileType.FILE_TYPE_IMAGE;
                }
            };
            allDatas.add(entity);
        }
    }

    @Override
    public void terminateAbility() {
        super.terminateAbility();
        getFractionAbility().terminateAbility();
    }

    private void setImageCountTitle(int position) {
        mImageShowCountText.setText((position + 1) + "/" + mImageShowProvider.getCount());
        IBaseFileEntity entity = mImageShowProvider.getItem(position);
        if (entity != null) {
            nameText.setText(entity.getFileName());
        }

    }

    /**
     * 删除图片
     */
    private void deletePicture() {
        final int currentPagePosition = mImageShowPageSlide.getCurrentPage();
        IBaseFileEntity entity = mImageShowProvider.getItem(currentPagePosition);
        if (entity != null && !TextTool.isNullOrEmpty(entity.getFilePath())) {
            //物理删除
            File file = new File(entity.getFilePath());
            boolean isSuccess = file.delete();
            if (isSuccess) {
                setResultChanged();
                int deleteIndex = allDatas.indexOf(entity);
                allDatas.remove(entity);
                refreshPageSlide(deleteIndex);
            }
        }
    }

    /**
     * 设置结果变化回调
     */
    private void setResultChanged() {
        Intent intent = new Intent();
        intent.setParam(Constant.HAS_CHANGED, true);
        setResult(Constant.DATA_CHANGED_CODE, intent);
    }

    /**
     * 刷寻组件
     *
     * @param deleteIndex
     */
    private void refreshPageSlide(int deleteIndex) {
        if (allDatas == null || allDatas.size() == 0) {
            ///退出页面
            terminateAbility();
        } else {
            //这里实际上就是对provider内部数据进行删除操作并更新UI，没必要重新初始化数据
            mImageShowProvider.deleteItem(deleteIndex);
            //setCurrentPage默认带了滚动动效，需要手动将smoothScroll置为false，否则动画效果会造成视觉残留，经测试，该方法内部对index范围超出做了判断，外部可以不用判断
            mImageShowPageSlide.setCurrentPage(deleteIndex, false);
        }
    }
}
